//
//  HACStockDetailView.m
//  Pods
//
//  Created by Hotacool on 2017/9/1.
//
//

#import "HACStockDetailView.h"
#import "HACTimeLineView.h"
#import "HACTecView.h"
#import "HACBasicComponents.h"
#import "HACTimeLineEntry.h"

@interface HACStockDetailView () <UIScrollViewDelegate>
/** 当前焦点所在index */
@property (nonatomic) NSInteger focusIndex;

@property (nonatomic) NSInteger focusItemsCount; /** 默认1，只绘制竖线，需要绘制横线指示设置成2 */

// 处理缩放
@property (nonatomic) CGFloat minScale;     /** 可以缩放最小值，默认0.3倍 */
@property (nonatomic) CGFloat maxScale;     /** 可以缩放最大值，默认3倍 */
@property (nonatomic) CGFloat effectScale;  /** 每次变化生效阀值 */
@property (nonatomic) CGFloat lastScale;    /** 上一次缩放比例 */
@property (nonatomic) CGFloat lastEndScale; /** 上次结束最后缩放值，也是当次初始值，用于指示当前相对默认的比例 */

@property (nonatomic, strong) UILabel *xCursorLabel; // y轴的文字提示
@property (nonatomic, strong) UILabel *yCursorLabel; // x轴的文字提示
@property (nonatomic, strong) CAShapeLayer *focusLayer;

@property (nonatomic, strong) HACTimeLineView *timeLineView;
@property (nonatomic, strong) HACTecView *tecView;

@end

@implementation HACStockDetailView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor clearColor];
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        self.alwaysBounceHorizontal = YES;
        self.alwaysBounceHorizontal = YES; // 保证可以滑动和最后回到offset为0
        self.delegate = self;
        
        self.focusItemsCount = 2;
        
        // 点击手势
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
        [self addGestureRecognizer:tapGesture];
        
        // 添加长按手势
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGesture:)];
        longPressGesture.delegate = self;
        longPressGesture.minimumPressDuration = 0.5;
        [self addGestureRecognizer:longPressGesture];
        
        // 添加缩放手势
        UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGesture:)];
        [self addGestureRecognizer:pinchGesture];
        
        //分时图
        _timeLineView = [[HACTimeLineView alloc] initWithFrame:CGRectMake(5, 5, frame.size.width-10, frame.size.height*.6)];
        [self addSubview:_timeLineView];
        //指标 量
        _tecView = [[HACTecView alloc] initWithFrame:CGRectMake(5, CGRectGetMaxY(_timeLineView.frame)+20, frame.size.width-10, frame.size.height-_timeLineView.frame.size.height-30)];
        [_tecView setViewType:HACTecViewTypeTimeLine andIndexType:HACTecViewIndexTypeVol];
        [self addSubview:_tecView];
        
        // 添加focus
        self.focusIndex = -1;
        self.focusLayer = [[CAShapeLayer alloc] init];
        self.focusLayer.frame = self.bounds;
        self.focusLayer.backgroundColor = [[UIColor clearColor] CGColor];
        self.focusLayer.contentsScale = [[UIScreen mainScreen] scale];
        self.focusLayer.strokeColor = [UIColor blackColor].CGColor;
        [self.layer addSublayer:self.focusLayer];
        
        //focus文字
        self.xCursorLabel = [[UILabel alloc] init];
        self.xCursorLabel.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.5];
        self.xCursorLabel.layer.borderColor = [UIColor brownColor].CGColor;
        self.xCursorLabel.layer.borderWidth = 1;
        [self addSubview:self.xCursorLabel];
        
        self.yCursorLabel = [[UILabel alloc] init];
        self.yCursorLabel.backgroundColor = [UIColor colorWithWhite:0.9 alpha:0.5];
        self.yCursorLabel.layer.borderColor = [UIColor brownColor].CGColor;
        self.yCursorLabel.layer.borderWidth = 1;
        [self addSubview:self.yCursorLabel];
    }
    return self;
}

- (void)refreshWithData:(HACChartData *)data {
    _data = data;
    [self.timeLineView setData:data];
    [self.tecView setData:data];
    [self setNeedsDisplay];
    //test
    self.contentSize = CGSizeMake(1000, self.bounds.size.height);
}

#pragma mark - gestures
#pragma mark ----- UIGestureRecognizer
- (void)tapGesture:(UITapGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:self];
    
}

- (void)longPressGesture:(UILongPressGestureRecognizer *)gesture {
    CGPoint point = [gesture locationInView:self];
    if (gesture.state == UIGestureRecognizerStateBegan || gesture.state == UIGestureRecognizerStateChanged) {
        self.focusIndex = [self.timeLineView indexAtChartForCoordinate:point];;
    } else {
        self.focusIndex = -1;
    }
    [self drawingFocusLayer];
}

- (void)pinchGesture:(UIPinchGestureRecognizer *)gesture {
    
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

#pragma mark - provider
- (NSArray *)focusDataInRect:(CGRect)rect focusIndex:(NSInteger)focusIndex {
    if (self.focusItemsCount == 0 || focusIndex >= self.timeLineView.actualCount || focusIndex == -1)
        return nil;
    
    NSMutableArray *focusDrawingData = [NSMutableArray array];
    CGFloat x = 0.0, y = 0.0;
    for (NSInteger i = 0; i < self.focusItemsCount; i++) {
        HACFocusComponents *item = [[HACFocusComponents alloc] init];
        item.index = i;
        item.axisType = i == 0 ? DrawingAxisTypeY : DrawingAxisTypeX; //第一根是竖线，第二根横线
        item.text = [self stringForFocusItem:item focusIndex:focusIndex];
        
        CGSize textSize = [item.text sizeWithAttributes:@{NSFontAttributeName : item.textFont}];
        CGRect frame = CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), textSize.width , textSize.height);
        CGLine line = CGLineMake(0, 0, 0, 0);
        
        CGPoint focusPoint = [self.timeLineView pointAtChartForIndex:focusIndex];
        CGFloat offsetX = CGRectGetMinX(self.timeLineView.frame);
        CGFloat offsetY = CGRectGetMinY(self.timeLineView.frame);
        focusPoint = CGPointMake(focusPoint.x + offsetX, focusPoint.y + offsetY);
        
        if (item.axisType == DrawingAxisTypeX) {
            y = focusPoint.y;
            line = CGLineMake(CGRectGetMinX(rect) + textSize.width, y, CGRectGetMaxX(rect), y);
            frame.origin.y = MIN(CGRectGetMaxY(rect), MAX(CGRectGetMinY(rect), y - textSize.height / 2));
        } else {
            x = focusPoint.x;
            line = CGLineMake(x, CGRectGetMinY(rect), x, CGRectGetMaxY(rect));
            frame.origin.x = MIN(CGRectGetMaxX(rect) - textSize.width, MAX(CGRectGetMinX(rect), x - textSize.width / 2));
            frame.origin.y = CGRectGetMaxY(rect);
        }
        
        item.textFrame = frame;
        item.line = line;
        [focusDrawingData addObject:item];
    }
    return focusDrawingData;
}

#pragma  markt - drawing
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    
}

- (void)drawingFocusLayer {
    if (self.focusIndex == -1) {
        // 清除
        self.focusLayer.path = NULL;
        self.xCursorLabel.hidden = YES;
        self.yCursorLabel.hidden = YES;
    } else {
        self.xCursorLabel.hidden = NO;
        self.yCursorLabel.hidden = NO;
        
        @autoreleasepool {
            CGMutablePathRef path = CGPathCreateMutable();
//            CGRect offsetCenterFrame = [self offsetRectForOriginalRect:self.timeLineView.frame];
            CGRect offsetCenterFrame = self.timeLineView.frame;
            NSArray *datas = [self focusDataInRect:offsetCenterFrame focusIndex:self.focusIndex];
            
            for (HACFocusComponents *obj in datas) {
                UILabel *label = obj.axisType == DrawingAxisTypeX ? self.xCursorLabel : self.yCursorLabel;
                label.text = obj.text;
                label.frame = obj.textFrame;
                label.font = obj.textFont;
                label.textColor = obj.textColor;
                
                CGLine line = obj.line;
                if (obj.axisType == DrawingAxisTypeY) {
                    // y轴需要从最上面到最下面
                    line.start.y = 0;
                    line.end.y = CGRectGetMaxY(self.bounds);
                }
                CGPathMoveToPoint(path, NULL, line.start.x, line.start.y);
                CGPathAddLineToPoint(path, NULL, line.end.x, line.end.y);
            }
            self.focusLayer.path = path;
            CFRelease(path);
        }
    }
}

-(CGRect)offsetRectForOriginalRect:(CGRect)originalRect {
    CGRect offsetRect = CGRectMake(self.contentOffset.x + originalRect.origin.x, self.contentOffset.y + originalRect.origin.y, originalRect.size.width, originalRect.size.height);
    return offsetRect;
}

- (NSString *)stringForFocusItem:(HACFocusComponents *)focusItem focusIndex:(NSInteger)focusIndex {
    NSString *focusString;
    HACTimeLineEntry *data = [self.timeLineView dataAtChartForIndex:focusIndex];
    if (focusItem.axisType == DrawingAxisTypeX) {
        focusString = @(data.newprice).stringValue;
    }
    return focusString;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    self.timeLineView.frame = CGRectMake(offset.x, self.timeLineView.frame.origin.y, self.timeLineView.frame.size.width, self.timeLineView.frame.size.height);
    self.tecView.frame = CGRectMake(offset.x, self.tecView.frame.origin.y, self.tecView.frame.size.width, self.tecView.frame.size.height);
}
@end
